package com.cly.cart.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cly.cart.service.CartService;
import com.cly.common.entity.cart.po.Cart;
import com.cly.common.util.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class OrderSuccessListener {

    private final CartService cartService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "order.success.cart.delete", durable = "true"),
            exchange = @Exchange(name = "cart.clear.queue", type = "direct"),
            key = "order.create",
            arguments = @Argument(name = "x-queue-mode", value = "lazy") // 队列模式,指定为惰性队列，性能更好
    ))
    public void deleteCart(Map<String, Object> itemIdListAndUserId) {
        List<Long> itemIdList = (List<Long>) itemIdListAndUserId.get("itemIdList");
        Long userId = (Long) itemIdListAndUserId.get("userId");
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, userId)
                .in(Cart::getItemId, itemIdList);
        cartService.remove(queryWrapper);
    }
}
